package com.hmtech.ayp.common.typehandler;

import cn.hutool.core.util.StrUtil;
import com.hmtech.ayp.common.s3.service.IS3Service;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 闫家洪（yanjiahong@vcredit.com）
 * @since 2023/5/10
 */
@Slf4j
@Component
public class S3UrlTypeHandler implements TypeHandler<String> {

    @Autowired
    private IS3Service s3Service;

    @Override
    public void setParameter(PreparedStatement ps, int i, String s, JdbcType jdbcType) throws SQLException {
        ps.setString(i, s);
    }

    @Override
    public String getResult(ResultSet resultSet, String columnName) throws SQLException {
        return s3Key2PublicUrl(resultSet.getString(columnName));
    }

    @Override
    public String getResult(ResultSet resultSet, int i) throws SQLException {
        return s3Key2PublicUrl(resultSet.getString(i));
    }

    @Override
    public String getResult(CallableStatement callableStatement, int i) throws SQLException {
        return s3Key2PublicUrl(callableStatement.getString(i));
    }

    private String s3Key2PublicUrl(String text) {
        try {
            // 如果是空字符串或者不是OssKey的开头，原样返回
            if (StrUtil.isEmpty(text) || text.startsWith("https://")) {
                return text;
            }
            // 是OssKey开头，生成公开url
            return s3Service.genPreSignedUrlForGet(text);
        } catch (Exception e) {
            log.error("OSSKey转换为公开url出错！text: " + text, e);
            return text;
        }
    }
}
